package com.dragon.modules.yuegou.service.impl.member;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.exception.DragonException;
import com.dragon.modules.yuegou.entity.member.LevelEntity;
import com.dragon.modules.yuegou.enums.code.BusinessCode;
import com.dragon.modules.yuegou.enums.code.MemberCode;
import com.dragon.modules.yuegou.enums.member.LevelCycle;
import com.dragon.modules.yuegou.mapper.member.LevelMapper;
import com.dragon.modules.yuegou.model.member.Level;
import com.dragon.modules.yuegou.query.member.LevelQuery;
import com.dragon.modules.yuegou.service.member.LevelService;
import com.dragon.modules.yuegou.web.Check;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 会员等级表 服务实现
 *
 * @author pbuilder generated
 * @date 2019-03-19 08:59:40
 * @version 2.0
 */
@Slf4j
@Service("memLevelService")
public class LevelServiceImpl
		extends ServiceImpl<LevelMapper, LevelEntity>
		implements LevelService {

	@Override
	public Level getLowestLevel(String busdId) {
		if(busdId==null){
			return null;
		}

		LevelQuery levelQuery = new LevelQuery();
		levelQuery.setBusdId(busdId);
		levelQuery.setSerialNumber(1);
		levelQuery.setDel(false);
		List<LevelEntity> list = list(levelQuery.toQueryWrapper());
		if (CollectionUtils.isNotEmpty(list)){
			return new Level(list.get(0));
		}
		return null;
	}


	/**
	 * 根据会员等级有效期 计算结束时间
	 * @param startTime
	 * @return 返回日期
	 * @throws
	 */
	public LocalDateTime getValidityEndTime(LocalDateTime startTime, LevelCycle memberCycle) {
		if (startTime ==null){
			startTime = LocalDateTime.now();
		}
		if (memberCycle==null){
			return  LocalDateTime.now();
		}
		try {
			LocalDateTime lastTime = LocalDateTime.now();
			//日期转date
			Calendar calendar =Calendar.getInstance();
			ZoneId zone = ZoneId.systemDefault();
			Instant instant = startTime.atZone(zone).toInstant();
			Date date = Date.from(instant);
			calendar.setTime(date);

			switch (memberCycle){
				case THATYEAR:
					//当年
					lastTime = LocalDateTime.of(startTime.getYear(),12,31,23,59,59);
					break;
				case THATMONTH:
					//当月
					//当月最后一天
					LocalDateTime lastDayOfThisMonth = startTime.with(TemporalAdjusters.lastDayOfMonth());
					lastTime = LocalDateTime.of(startTime.getYear(),startTime.getMonth(),lastDayOfThisMonth.getDayOfMonth(),23,59,59);
					break;
				case ROLLINGYEAR:
					//滚动年
					//一年之后
					calendar.add(calendar.YEAR, 1);
					calendar.add(calendar.DAY_OF_YEAR,-1);

					date = calendar.getTime();

					Instant newInstant = date.toInstant();
					ZoneId newZone = ZoneId.systemDefault();
					lastTime =LocalDateTime.ofInstant(newInstant, newZone);
					break;
				case ROLLINGMONTH:
					//滚动月
					calendar.add(calendar.MONTH, 1);
					calendar.add(calendar.DAY_OF_YEAR,-1);

					date = calendar.getTime();

					Instant monthInstant = date.toInstant();
					ZoneId monthZone = ZoneId.systemDefault();

					lastTime = LocalDateTime.ofInstant(monthInstant, monthZone);
					break;
				default:
					break;
			}
			return  lastTime;
		} catch (Exception e) {
			return LocalDateTime.now();
		}
	}

	public Integer getLevelNum(String busdId){
		Check.notNull(busdId, BusinessCode.BUSDID_NOTNULL.getMessage());
		return baseMapper.getLevelNum(busdId)+1;
	}

	public void saveLevel(Level level){
		Check.notNull(level.getBusdId(),BusinessCode.BUSDID_NOTNULL.getMessage());
		Check.notNull(level.getSerialNumber(),"等级编号不能为空");
		Check.notEmpty(level.getName(),"等级名称不能为空");
		Check.notNull(level.getObtainPoints(),"获取积分不能为空");
		Check.positive(level.getObtainPoints(),"获取积分不能为负数");
		Check.digits(level.getObtainPoints(),10,0,"获取积分必须是正整数");
		Check.notNull(level.getOriginalPoints(),"原始积分不能为空");
		Check.positive(level.getOriginalPoints(),"原始积分不能为负数");
		Check.digits(level.getOriginalPoints(),10,0,"原始积分必须是正整数");
		Check.notNull(level.getCycle(),"有效期不能为空");
		Check.notEmpty(level.getImg(),"等级图标不能为空");
		log.info("保存会员等级，开始==，等级名称={}", level.getName());
		if (StringUtils.isEmpty(level.getRights()) && StringUtils.isEmpty(level.getRightsImg())) {
			throw new DragonException(MemberCode.EQUITY_DESCRIPTION_EQUITY_PICTURE_CAN_NOT_BE_EMPTY);
		}
		//查询等级名称是否存在于商圈
		LevelQuery query = new LevelQuery();
		query.setBusdId(level.getBusdId());
		query.setName(level.getName());
		List<LevelEntity> list = list(query.toQueryWrapper());
		if (!StringUtils.isEmpty(level.getId())) {
			if (list.size() > 0 && !list.get(0).getId().equals(level.getId())) {
				log.info("修改会员等级，等级名称存在，等级名称={}", level.getName());
				throw new DragonException(MemberCode.MEMBER_LEVEL_EXIST);
			}
			//修改会员等级
			baseMapper.updateById(level);
			log.info("保存会员等级，修改成功，等级名称={}", level.getName());
		}else {
			if (list.size() > 0) {
				log.info("新增会员等级，等级名称存在，等级名称={}", level.getName());
				throw new DragonException(MemberCode.MEMBER_LEVEL_EXIST);
			}
			//新增会员等级
			save(level);
			log.info("保存会员等级，修改成功，等级名称={}", level.getName());
		}
	}
}